﻿using Microsoft.Office.Interop.PowerPoint;
using System;
using System.IO;

namespace OfficeConvert.Core
{
    /// <summary>
    /// PowerPoint转换类
    /// </summary>
    public class PowerPointConvert : IOfficeConvert
    {
        public bool Convert(string sourceFullName, string targetFullName)
        {
            var extensionName = Path.GetExtension(targetFullName);

            switch (extensionName.ToUpper())
            {
                case ".JPG":
                    return ConvertFileFormat(sourceFullName, targetFullName, PpSaveAsFileType.ppSaveAsJPG);
                case ".GIF":
                    return ConvertFileFormat(sourceFullName, targetFullName, PpSaveAsFileType.ppSaveAsGIF);
                case ".MP4":
                    return ConvertFileFormat(sourceFullName, targetFullName, PpSaveAsFileType.ppSaveAsMP4);
                case ".PDF":
                    return ConvertFileFormat(sourceFullName, targetFullName, PpSaveAsFileType.ppSaveAsPDF);
                case ".XPS":
                    return ConvertFileFormat(sourceFullName, targetFullName, PpSaveAsFileType.ppSaveAsXPS);
                default:
                    throw new Exception($"不支持的文件类型：{extensionName}");
            }
        }

        bool ConvertFileFormat(string sourceFullName, string targetFullName, PpSaveAsFileType ppSaveAsFileType)
        {
            ApplicationClass application = null;
            Presentation persentation = null;

            try
            {
                application = new ApplicationClass();
                persentation = application.Presentations.Open(sourceFullName);
                persentation.SaveAs(targetFullName, ppSaveAsFileType);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            finally
            {
                persentation?.Close();
                application?.Quit();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return true;
        }
    }
}
